package com.smartshopping.iu;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import com.smartshopping.model.*;
import com.smartshopping.view.ImageLoader;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class GoodDetailActivity extends Activity {

	private DataBaseHelper myDbHelper;
	private int numberBuy = 0;
	private Intent resultData;
	private int itemID = 0;
	private String name =null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_good_detail);
		//Must create fisrt
		resultData = new Intent();
		createDetail();
		
		//Create intent
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		this.numberBuy = Integer.parseInt(extras.getString("numberBuy"));
		((TextView)findViewById(R.id.good_detail_number_buy)).setText("Mua hàng: " + Integer.toString(numberBuy));
		resultData.putExtra("numberBuy", Integer.toString(numberBuy));
		
		//Create the delete numberbuy button
		ImageButton deleteBuyButton = (ImageButton) findViewById(R.id.good_detail_imageButton_notbuy);
		deleteBuyButton.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	numberBuy = 0;
	        	((TextView)findViewById(R.id.good_detail_number_buy)).setText("Mua hàng: " + "0");
	        }
	    });
		
		//Create the add numberbuy button
		ImageButton addBuyButton = (ImageButton) findViewById(R.id.good_detail_imageButton_add);
		addBuyButton.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	numberBuy++;
	        	((TextView)findViewById(R.id.good_detail_number_buy)).setText("Mua hàng: " + Integer.toString(numberBuy));
	        }
	    });
		
		//Create the subtract numberbuy button
		ImageButton subBuyButton = (ImageButton) findViewById(R.id.good_detail_imageButton_sub);
		subBuyButton.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	if (numberBuy > 0) numberBuy--;
	        	((TextView)findViewById(R.id.good_detail_number_buy)).setText("Mua hàng: " +  Integer.toString(numberBuy));
	        }
	    });
		
		//Create finish button
		ImageButton finishBuyButton = (ImageButton) findViewById(R.id.good_detail_imageButton_finish);
		finishBuyButton.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	resultData.putExtra("numberBuy", Integer.toString(numberBuy));
	    		setResult(Activity.RESULT_OK, resultData);
	        	finish();
	        }
	    });
	}

	public void createDetail()
	{
		TextView name = ((TextView)findViewById(R.id.good_detail_name));
		TextView price = ((TextView)findViewById(R.id.good_detail_price));
		TextView description = ((TextView)findViewById(R.id.good_detail_description));
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		
		//Get the value of itemID and name;
		this.itemID = Integer.parseInt(extras.getString("itemID"));
		this.name = extras.getString("name");
		name.setText(extras.getString("name"));
		myDbHelper = new DataBaseHelper(this);
		try 
		{
			myDbHelper.createDataBase(this);
		} catch (IOException ioe) 
		{
		 		throw new Error("Unable to create database");
		}
		SQLiteDatabase mdb = myDbHelper.getReadableDatabase();
		final String sql = "select cost.Value, description.More, description.Url from cost " +
				"inner join item on item._id = cost.ItemID " +
				"inner join coop on coop._id = cost.CoopID " +
				"inner join description on description._id = item._id " + 
				"where (item._id = " + extras.getString("itemID") + " and coop._id = " + extras.getString("coopID") + ") ";
		System.out.println(sql);
		Cursor mCursor = mdb.rawQuery(sql, null); 	
		if(mCursor.moveToFirst()){
			try
			  {
				ImageView image = (ImageView)findViewById(R.id.good_detail_image);
		     // Loader image - will be shown before loading image
		        int loader = R.drawable.itemdetail;
		        // Image url
		        String image_url = mCursor.getString(2);
		        // ImageLoader class instance
		        ImageLoader imgLoader = new ImageLoader(getApplicationContext());
		        // whenever you want to load an image from url
		        // call DisplayImage function
		        // url - image url to load
		        // loader - loader image, will be displayed before getting image
		        // image - ImageView
		        imgLoader.DisplayImage(image_url, loader, image);
			  }catch (Exception e) {
				   System.out.println("Exc="+e);
				  }
			resultData.putExtra("price",Integer.toString(mCursor.getInt(0)));
			price.setText("Price: " + Integer.toString(mCursor.getInt(0)));
			description.setText(mCursor.getString(1));
		}
		mCursor.close();
		mdb.close();
	}
	
	//Check is whether online or not
	public boolean isOnline() {
	    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
	        return true;
	    }
	    return false;
	}
	
	public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in, null, options);
            in.close();
        } catch (IOException e1) {
        }
        return bitmap;
    }
	
	private static InputStream OpenHttpConnection(String strURL)
            throws IOException {
        InputStream inputStream = null;
        URL url = new URL(strURL);
        URLConnection conn = url.openConnection();

        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setRequestMethod("GET");
            httpConn.connect();

            if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpConn.getInputStream();
            }
        } catch (Exception ex) {
        }
        return inputStream;
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.index, menu);
		return true;
	}

}
